package com.wuchengdong.web.controller;

import com.wuchengdong.web.extend.utils.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 管理文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    String staticResourcePath = "E:\\tmp\\";

    @PostMapping
    public R<String> upload(MultipartFile file){
        if (file.isEmpty()) {
            return R.error("文件为空");
        }
        log.info(file.toString());
        //1.使用UUID生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID() +suffix;
        //2.转存到程序资源目录
        File dir = new File(staticResourcePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(staticResourcePath,newFilename));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(newFilename);
    }

    @GetMapping
    public R<String> download(String name, HttpServletResponse response){
        try {
            FileInputStream inputStream = new FileInputStream(new File(staticResourcePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            response.setContentType("image/jpeg");
            inputStream.close();
            outputStream.close();
        } catch (IOException ignored) {

        }
        return R.success("下载成功");
    }
}
